"use strict";

!function () {
	var itemIndex = 0;
	var flag = 0;
	// 判断是否有这个类
	function hasClass(el, className) {
		if (el && el.className !== void 0) {
			var classList = el.className.split(/\s+/);
			if (classList.indexOf(className) >= 0) {
				return true;
			} else return false;
		} else {
			return false;
		}
	}

	// 删除这个类
	function deleteClass(el, className) {
		if (hasClass(el, className)) {
			var classList = el.className.split(/\s+/);
			var deleteIndex = classList.indexOf(className);
			classList.splice(deleteIndex, 1);
			el.className = classList.join(' ');
		} else {
			return;
		}
	}

	// 添加这个类
	function addClass(el, className) {
		if (hasClass(el, className)) {
			return false;
		} else {
			var classList = el.className.split(/\s+/);
			classList.push(className);
			el.className = classList.join(" ");
		}
	}

	// 清空所有的active类
	function mapRemove(sameEl, className) {
		var tagEl = document.getElementsByClassName(sameEl);
		for (var i = 0, j = tagEl.length; i != j; i++) {
			deleteClass(tagEl[i], className);
		}
	}

	// 对dot绑定点击事件。清空所有active，然后对特定的绑定active
	function bindDot() {
		var tagDot = document.getElementsByClassName("dot-container")[0];
		tagDot.addEventListener("click", function (e) {
			var target = e.target;
			if (hasClass(target, "dot")) {
				if (itemIndex === target.dataset.index) {
					return;
				} else {
					itemIndex = target.dataset.index;
					mapRemove("img", "active");
					addActive("img", itemIndex - 1);
				}
			} else {
				return;
			}
		});
	}

	// 对前后按钮绑定点击事件
	function bindBottom() {
		var buttonParent = document.getElementsByClassName("button")[0];
		buttonParent.addEventListener("click", function (e) {
			var target = e.target;
			if (target.className === "up") {
				itemIndex--;
				if (itemIndex < 1) {
					itemIndex = 5;
				}
				mapRemove("img", "active");
				addActive("img", itemIndex - 1);
			} else if (target.className === "down") {
				itemIndex++;
				if (itemIndex > 5) {
					itemIndex = 1;
				}
				mapRemove("img", "active");
				addActive("img", itemIndex - 1);
			} else {
				return;
			}
		});
	}

	// 为正确的index增加active类
	function addActive(el, index) {
		var dom = document.getElementsByClassName(el);
		addClass(dom[index], "active");
	}

	// 鼠标暂停
	function mousehover() {
		var tag = document.getElementsByClassName("container")[0];
		tag.addEventListener("mouseenter", function () {
			if (flag) {
				clearTimeout(flag);
			}
		});
		tag.addEventListener("mouseleave", function () {
			setinter();
		});
	}

	function bindEvent() {
		bindDot();
		bindBottom();
		mousehover();
	}

	// 执行绑定事件
	bindEvent();

	// 设置定时器函数
	function setinter() {
		itemIndex++;
		if (itemIndex > 5) {
			itemIndex = 1;
		}
		mapRemove("img", "active");
		addActive("img", itemIndex - 1);
		console.log(itemIndex);
		flag = setTimeout(setinter, 3000);
	}
	setinter();

	// 
}();